<?php
class RedisSessionHandler{
    public $ttl = 1800; // 30 minutes default
    protected $db;
    protected $prefix;
    public function __construct($db, $prefix = 'PHPSESSID1:',$time=1800) {
        $this->db = $db;
        $this->prefix = $prefix;
        $this->ttl =  $time;
    }
    function _open()
    {
        //
    }

    function _close()
    {
        $this->db = null;
        unset($this->db);
    }

    function _read($id)
    {
        $id = $this->prefix . $id;
        $sessData = $this->db->get($id);
        // $this->db->expire($id, $this->ttl);
        return $sessData;
    }

    function _write($id, $data)
    {
        $id = $this->prefix . $id;
        $this->db->set($id, $data);
        // $this->db->expire($id, $this->ttl);
    }

    function _destroy($id)
    {
        $this->db->del($this->prefix . $id);
    }

    function _clean($max)
    {
        //
    }
}

define( 'User_AK' , 'db2e3c65aa0f47bbab9bea0764dadaf7' );
define( 'User_SK' , '9c7bcac8432f48939c43b28d4e61844d' );

/*从平台获取数据库名*/
$dbname = "UDICLzcDirLTMJFuxFSD"; //数据库名称

/*从环境变量里取host,port,user,pwd*/
$host = 'redis.duapp.com';
$port = '80';
$user = User_AK; //用户AK
$pwd = User_SK;  //用户SK

try {
    /*建立连接后，在进行集合操作前，需要先进行auth验证*/
    $redis = new Redis();
    $ret = $redis->connect($host, $port);
    if ($ret === false) {
        die($redis->getLastError());
    }

    $ret = $redis->auth($user . "-" . $pwd . "-" . $dbname);
    if ($ret === false) {
        die($redis->getLastError());
    }

    /*接下来就可以对该库进行操作了，具体操作方法请参考phpredis官方文档*/
/**    
    $redis->flushdb();
    $ret = $redis->set("key", "value");
    if ($ret === false) {
        die($redis->getLastError());
    } else {
        echo "OK";
    }
**/

    $SESSION_ID_PREFIX = 'RSID:';
    $SESSION_MAX_TIME  = 1440;
    ini_set('session.gc_maxlifetime',$SESSION_MAX_TIME);
    $sessHandler = new RedisSessionHandler($redis,$SESSION_ID_PREFIX,$SESSION_MAX_TIME);
    session_set_save_handler(
        array($sessHandler, '_open'),
        array($sessHandler, '_close'),
        array($sessHandler, '_read'),
        array($sessHandler, '_write'),
        array($sessHandler, '_destroy'),
        array($sessHandler, '_clean')
    );

} catch (RedisException $e) {
    die("Uncaught exception " . $e->getMessage());
}

/**

$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$redis->select(1);
$SESSION_ID_PREFIX = 'RSID:';
$SESSION_MAX_TIME  = 1440;
ini_set('session.gc_maxlifetime',$SESSION_MAX_TIME);
$sessHandler = new RedisSessionHandler($redis,$SESSION_ID_PREFIX,$SESSION_MAX_TIME);
session_set_save_handler(
    array($sessHandler, '_open'),
    array($sessHandler, '_close'),
    array($sessHandler, '_read'),
    array($sessHandler, '_write'),
    array($sessHandler, '_destroy'),
    array($sessHandler, '_clean')
);

session_start();
echo session_id();
echo $_SESSION['name']='zhangcunchao';

*/
